import { ref, computed } from 'vue'

const serialize = value => {
  if (
    typeof value === 'number'
    || typeof value === 'boolean'
    || typeof value === 'string'
  ) {
    return value
  } else if (value !== null && typeof value === 'object') {
    return JSON.stringify(value)
  } else {
    return null
  }
}

const deserialize = val => {
  return JSON.parse(val)
}

export default function useStorage(key, value) {
  const state = ref(serialize(value))
  localStorage.setItem(key, state.value)

  return computed({
    get() {
      return deserialize(state.value)
    },
    set(val) {
      state.value = serialize(val)
      localStorage.setItem(key, state.value)
    },
  })
}
